package cn.tedu.csmall.resource.controller;

import io.minio.MinioClient;
import io.minio.ObjectWriteArgs;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.UUID;
@RestController
@Slf4j
public class MinioUploadController {
    public MinioUploadController(){
        log.info("MinioUploadController()");
    }

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.bucket}")
    private String bucket;

    @Value("${minio.object-key-prefix}")
    private String objectKeyPrefix;

    /**
     * @RequestPart 用于描述MultipartFile类型，并可以
     * 指定客户端要传递的属性名是什么
     * @param picFile
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/minio/upload", method = RequestMethod.POST)
    public String doUpload(@RequestPart("picFile") MultipartFile picFile) throws Exception{
        //1.为文件重命名
        String originalFilename=picFile.getOriginalFilename();
        String newFileName=UUID.randomUUID()+
                originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectKey = objectKeyPrefix + newFileName;

        ObjectWriteResponse res = minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucket)
                .object(objectKey)
                .contentType(picFile.getContentType())
                .stream(picFile.getInputStream(), picFile.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build());
        // 返回可访问的图片链接
        return endpoint + bucket + objectKey;
    }

}